package com.utonw.carloan.activity.applyloan;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.utonw.carloan.R;
import com.utonw.carloan.function.GlobalLoanFunction;
import com.utonw.carloan.global.Constants;
import com.utonw.carloan.global.ReleaseData;
import com.utonw.carloan.utils.FileUtils;
import com.utonw.carloan.utils.ImageUtils;
import com.utonw.carloan.utils.LogUtil;
import com.utonw.carloan.utils.UIUtils;

import java.io.File;


/**
 * Created by SEELE on 2017/4/5.
 */

public class ShowPreviewsImageActivity extends Activity {
    //获得的Bitmap
    private Bitmap mBmp;
    //删除图片
    private TextView mDeleteImage;
    //修改图片
    private TextView mChangeImage;
    //判断是否修改过图片
    private boolean isChange = false;
    //初始化全局方法
    private GlobalLoanFunction mGlobalLoanFunction;
    //ImageView对象
    private ImageView mImagePreviews;
    //获取的屏幕宽度
    private int mMeasureWidth;
    //获取的屏幕高度
    private int mMeasureHeight;
    //修改后的图片文件路径
    private String changedFilePath = null;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_pre_image);
        mImagePreviews = (ImageView) findViewById(R.id.iv_previews);
        final LinearLayout tapToFinish = (LinearLayout) findViewById(R.id.ll_tap_to_finish);
        TextView title1 = (TextView) findViewById(R.id.tv_image_pre_title);
        mDeleteImage = (TextView) findViewById(R.id.tv_btn_delete_image);
        mChangeImage = (TextView) findViewById(R.id.tv_btn_change_image);
        //初始化
        mGlobalLoanFunction = new GlobalLoanFunction();

        //获取屏幕的长宽
        WindowManager wm = (WindowManager)
                getSystemService(Context.WINDOW_SERVICE);
        mMeasureWidth = wm.getDefaultDisplay().getWidth();
        mMeasureHeight = wm.getDefaultDisplay().getHeight();

        //获取接收的Intent
        Intent intent = getIntent();

        //获取接收的文件路径
        final String filePath = intent.getStringExtra("filePath");
        //接收标题
        int title = intent.getIntExtra("sTitle", -1);
        //设置标题
        title1.setText(title);

        //显示图片
        setImageByFilepath(mImagePreviews, mMeasureWidth, mMeasureHeight, filePath);

        //点击图片区域可返回
        tapToFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //根据flag判断是否修改过图片,如果修改则将修改后的图片路径传给target Image对象
                if (isChange) {
                    Intent intent = new Intent();
                    intent.putExtra("changedFilePath", changedFilePath);
                    setResult(Constants.RESULT_CHANGE_IMAGE, intent);
                }
                finish();
            }
        });


        //删除图片
        mDeleteImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置flag为不修改图片
                isChange = false;
                setResult(Constants.RESULT_DELETE_IMAGE);
                finish();
            }
        });


        //修改图片
        mChangeImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2017/4/7 需要获得修改后的图片文件的路径
                mGlobalLoanFunction.showGetImageDialog(ShowPreviewsImageActivity.this, null, new GlobalLoanFunction.SendPathInterface() {
                    @Override
                    public void sendCamFilePath(String path, Uri mImageUri) {
                        ReleaseData.tempPathFromCamera = path;
                        ReleaseData.tempUriFromCamera = mImageUri;
                    }
                });


            }
        });

    }

    private void setImageByFilepath(ImageView imagePreviews, int measureWidth, int measureHeight, String filePath) {
        try {
            mBmp = ImageUtils.decodeSampledBitmapFromFile(filePath, (int) Math.round(measureWidth * 0.8), (int) Math.round(measureHeight * 0.8));
            if (null != mBmp) {
                imagePreviews.setImageBitmap(mBmp);
            } else {
                UIUtils.showShortToast("文件不存在或已损坏");
                finish();
            }

        } catch (OutOfMemoryError | Exception e) {
            UIUtils.showShortToast("图片解析失败");
            finish();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取通过相册返回的图片URI
        if (requestCode == Constants.REQUEST_ALBUM && resultCode == RESULT_OK) {
            Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                do {
                    //设置flag已经修改了
                    isChange = true;
                    //存储新的文件路径
                    changedFilePath = FileUtils.getPath(this, data.getData());
                    //显示图片
                    setImageByFilepath(mImagePreviews, mMeasureWidth, mMeasureHeight, changedFilePath);

                } while (cursor.moveToNext());

                cursor.close();
            }


        }
        //获取通过相机返回的图片
        if (requestCode == Constants.REQUEST_CAMERA && resultCode == RESULT_OK) {

            LogUtil.d("照相返回的路径");
            LogUtil.d(ReleaseData.tempPathFromCamera);
            try {
                //设置flag已经修改了
                isChange = true;
                //存储新的文件路径
                changedFilePath = ReleaseData.tempPathFromCamera;
                //显示图片
                setImageByFilepath(mImagePreviews, mMeasureWidth, mMeasureHeight, changedFilePath);

            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }


            //用户取消拍照
        } else if (requestCode == Constants.REQUEST_CAMERA && resultCode == RESULT_CANCELED) {

            //删除报废的图片
            try {
                new File(ReleaseData.tempPathFromCamera).delete();

            } catch (Throwable e) {
                e.printStackTrace();
            }
            LogUtil.d("用户已取消照相");

        }

    }


    @Override
    protected void onDestroy() {
        //回收Bitmap
        if (null != mBmp && !mBmp.isRecycled()) {

            mBmp.recycle();

            mBmp = null;

        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
    }
}
